package com.ycu.jk16.mall.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ycu.jk16.mall.domain.User;
import com.ycu.jk16.mall.service.UserService;
import com.ycu.jk16.mall.util.common.ResponseJsonUtils;

/**
 * 
 * @ClassName UserController  
 * @Description TODO(UserController) 
 * @author 倪宗龙
 * @date 2018年12月11日 下午1:43:45  
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
	@Autowired
	@Qualifier("userService")
	private UserService userService;

	/**
	 * 
	 * @Title login 
	 * @Description TODO(用户登录) 
	 * @param  username 
	 * @param  password 
	 * @param  mav 
	 * @param  response 
	 * @return void @throws
	 */
	@RequestMapping(value = "/login")
	public void login(String username, String password, HttpServletResponse response) {

		Map<String, Object> data = new HashMap<String, Object>();
		User user = userService.login(username, password);
		System.out.println(username + " " + password);
		try {
			// 测试catch块
			user.getId();

			// 加入json数据
			data.put("status", 0);
			data.put("data", user);
		} catch (NullPointerException e) {
			data.put("status", 1);
			data.put("msg", "密码错误");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	/**
	 * 
	 * @Title register 
	 * @Description TODO(用户注册，这里后续可以加工更多验证信息) 
	 * @param username 
	 * @param password 
	 * @param email 
	 * @param phone 
	 * @param response 
	 * @return void @throws
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/register")
	public void register(String username, String password, String email, String phone, HttpServletResponse response)
			throws IllegalStateException, IOException {
		Map<String, Object> data = new HashMap<String, Object>();

		if (!userService.checkEmail(email) || !userService.checkUsername(username)) {
			data.put("status", 1);
			data.put("msg", "用户已存在");
		} else {
			User user = new User();
			// 将用户信息写入user
			user.setUsername(username);
			user.setPassword(password);
			user.setEmail(email);
			user.setPhone(phone);

			user.setCreateTime(new java.sql.Date(new Date().getTime()));
			user.setUpdateTime(new java.sql.Date(new Date().getTime()));
			userService.register(user);

			// json
			data.put("status", 0);
			data.put("msg", "注册成功");
		}

		ResponseJsonUtils.json(response, data);
	}

	/**
	 * 
	 * @Title checkValid
	 * @Description TODO(验证用户名或者邮箱是否可用)
	 * @param @param
	 *            str
	 * @param @param
	 *            type @param @return @return boolean @throws
	 */
	@RequestMapping(value = "/check_valid")
	public void checkValid(String str, String type, HttpServletResponse response) {
		boolean flag = false;
		Map<String, Object> data = new HashMap<String, Object>();

		if (type.equals("username")) {
			flag = userService.checkUsername(str);
		} else if (type.equals("email")) {
			flag = userService.checkEmail(str);
		}

		if (flag) {
			data.put("status", 0);
			data.put("data", "可以使用");
		} else {
			data.put("status", 1);
			data.put("msg", "用户名或者邮箱已存在");
		}

		ResponseJsonUtils.json(response, data);
	}

	@RequestMapping(value = "/get_user_info")
	public void getUserInfo(String id, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		User user = userService.findUserById(Integer.valueOf(id));

		try {
			user.getId();

			data.put("status", 0);
			data.put("data", user);
		} catch (NullPointerException e) {
			data.put("status", 1);
			data.put("msg", "用户未登录,无法获取信息");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/forget_get_question")
	public void forget_get_question(String username, String email, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		User user1 = userService.findUserByUsername(username);
		User user2 = userService.findUserByEmail(email);

		try {
			user1.getId();
			user2.getId();

			if (user1.getId() == user2.getId()) {
				data.put("status", 0);
				data.put("data", user1.getPassword());
			} else {
				data.put("status", 1);
				data.put("msg", "您的信息有误，无法找回");
			}
		} catch (NullPointerException e) {
			data.put("status", 1);
			data.put("msg", "用户未登录,无法获取信息");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/reset_password")
	public void reset_password(String username, String passwordOld, String passwordNew, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();

		User user = userService.findUserByUsername(username);

		try {
			if (user.getPassword().equals(passwordOld)) {
				// 更新密码
				user.setPassword(passwordNew);

				// 更新时间
				user.setUpdateTime(new java.sql.Date(new Date().getTime()));

				userService.updateUser(user);

				data.put("status", 0);
				data.put("msg", "修改密码成功");
			}

		} catch (NullPointerException e) {
			data.put("status", 1);
			data.put("msg", "旧密码输入错误");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/update_information")
	public void update_information(Integer id, String username, String password, String email,
			@RequestParam(required = false) CommonsMultipartFile headportraitUrl,
			String phone, HttpServletResponse response) throws IllegalStateException, IOException {
		Map<String, Object> data = new HashMap<String, Object>();

		User user = userService.findUserById(id);
		
		if (null != headportraitUrl) {
			user.setHeadPortraitUrl(savefile(headportraitUrl));
		}
		
		try {
			user.getId();
			
			if (!username.equals("")) {
				user.setUsername(username);
			}
			
			if (!password.equals("")) {
				user.setPassword(password);
			}
			
			if (!email.equals("")) {
				user.setEmail(email);
			}

			if (!phone.equals("")) {
				user.setPhone(phone);
			}

			// 更新时间
			user.setUpdateTime(new java.sql.Date(new Date().getTime()));
			userService.updateUser(user);

			data.put("status", 0);
			data.put("msg", "更新个人信息成功");

		} catch (NullPointerException e) {
			data.put("status", 1);
			data.put("msg", "信息有误，修改失败");
		} finally {
			ResponseJsonUtils.json(response, data);
		}

	}

	String savefile(CommonsMultipartFile file) throws IllegalStateException, IOException {
		String path = new Date().getTime() + file.getOriginalFilename();

		System.out.println(path);

		String dir = getClass().getResource("/").getPath();
		dir = dir.substring(0, dir.indexOf("WEB-INF"));
		File newFile = new File(dir + "Images/" + path);
		if (!newFile.exists()) {
			newFile.mkdirs();
		}
		file.transferTo(newFile);
		return path;
	}

	void delFile(String filename) {
		String dir = getClass().getResource("/").getPath();
		dir = dir.substring(0, dir.indexOf("WEB-INF"));
		File file = new File(dir + "Images/" + filename);
		if ((file.exists()) && (file.isFile())) {
			file.delete();
		}
	}
}
